//
// Created by hjie on 23-7-16.
//

#include "./../base/link.h"

void ProducerLinkList(LinkList & link_list, int number)
{
    srand(time(NULL));

    link_list.head_node = new LinkNode();
    link_list.tail_node = link_list.head_node;

    link_list.head_node->data = rand() % 50;
    link_list.head_node->next_node = nullptr;
    link_list.head_node->prev_node = nullptr;

    for (int index = 0; index < number - 1; index++)
    {
        int data = rand() % 50;
        LinkNode * node = new LinkNode();
        node->data = data;
        node->next_node = nullptr;
        node->prev_node = nullptr;

        link_list.tail_node->next_node = node;
        node->prev_node = link_list.tail_node;

        link_list.tail_node = node;
    }
    printf("producer data : ");
    LinkNode * ptr = link_list.head_node;
    while (ptr)
    {
        printf(" %d ", ptr->data);
        ptr = ptr->next_node;
    }
    printf("\n");
}
// compare two link list node if one node is equal that the link list is intersect
void IntersectingLinkList()
{
    int number = 10;
    LinkList list{};
    ProducerLinkList(list, number);

    LinkList list1{};
    ProducerLinkList(list1, number/2);

    LinkNode * p1 = list1.head_node;
    while (p1)
    {
        p1 = p1->next_node;
        if (rand() % 2 == 0)
        {
            printf("break.\n");
            break;
        }
    }
    if (p1)
    {
        list.tail_node->next_node = p1;
        list.tail_node = list1.tail_node;
    }
    LinkNode * first_node_p1  = list.head_node;
    LinkNode * second_node_p2 = list1.head_node;

    while (first_node_p1 != second_node_p2)
    {
        if (first_node_p1 == nullptr)
        {
            first_node_p1 = list1.head_node;
        }
        else
        {
            first_node_p1 = first_node_p1->next_node;
        }

        if (second_node_p2 == nullptr)
        {
            second_node_p2 = list.head_node;
        }
        else
        {
            second_node_p2 = second_node_p2->next_node;
        }
    }
    if (first_node_p1 == nullptr)
    {
        printf("no intersection.\n");
    }
    else
    {
        printf("has intersection.\n");
    }
}

int main(int argc, const char * argv[])
{
    IntersectingLinkList();
    return 0;
}